import { Algorithm } from "../types"

// 数据模型定义
interface HGPMSNode {
  id: any
  type: string
  attributes: Record<string, any>
}

interface HGPMSEdge {
  source: any
  target: any
  type?: string
  weight?: number
  attributes: Record<string, any>
}

interface HGPMSGraph {
  nodes: HGPMSNode[]
  edges: HGPMSEdge[]
}

interface Pattern {
  edge_patterns: {}
  node_types: {}
  id: string
  nodes: Record<string, number>  // 节点类型及数量
  edges: Record<string, number>  // 边类型及数量
  support: number
  instances: string[]  // 包含此模式的节点ID列表
}

interface HGPMSResult {
  patterns: Pattern[]
  pattern_growth_history: number[]
  pattern_instances: Record<string, any[]>
}

interface HGPMSInputParams {
  graph_data: HGPMSGraph   // 修改参数名
  min_support: number
  max_pattern_size: number
}

interface HGPMSOutputParams {
  results: HGPMSResult
  pattern_growth_history: number[]
  pattern_instances: Record<string, any[]>
  algorithm: string
  parameters: Record<string, any>
  execution_time: number
}

interface AlgorithmRequest {
  task_id: string
  task_callback_url?: string
  input_params: {
    hgpms_params: HGPMSInputParams
  }
}

// 添加一个更灵活的结果类型定义
interface FlexibleResults {
  patterns?: Pattern[];
  pattern_growth_history?: number[];
  [key: string]: any;
}

// 更灵活的输出参数类型
interface FlexibleOutputParams {
  results?: FlexibleResults;
  patterns?: Pattern[];
  pattern_growth_history?: number[];
  execution_time?: number;
  algorithm?: string;
  parameters?: Record<string, any>;
  [key: string]: any;
}

// 算法实现
export const HeterogeneousGraphPatternMining: Algorithm = {
  name: "异构图模式挖掘算法(HGPMS)",
  description: "基于异构图模式挖掘算法，用于识别和发现图中频繁出现的子图模式",
  configOptions: [
    {
      id: "min_support",
      label: "最小支持度",
      type: "number",
      defaultValue: 0.05,
      placeholder: "0.05"
    },
    {
      id: "max_pattern_size",
      label: "最大模式大小",
      type: "number",
      defaultValue: 4,
      placeholder: "4"
    },
    {
      id: "inputData",
      label: "输入数据",
      type: "textarea",
      placeholder: `请输入JSON格式的图数据，例如：
{
  "nodes": [
    {
      "id": "u1",
      "type": "用户",
      "attributes": {"age": 25, "gender": "男"}
    }
  ],
  "edges": [
    {
      "source": "u1",
      "target": "a1",
      "type": "发布",
      "weight": 1.0,
      "attributes": {"timestamp": "2023-01-01"}
    }
  ]
}`
    }
  ],
  execute: async (config) => {
    try {
      // 生成唯一的任务ID
      const taskId = `hgpms_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      // 解析输入数据
      let graphData: HGPMSGraph
      try {
        graphData = JSON.parse(config.inputData)
      } catch (e) {
        throw new Error("输入数据必须是有效的JSON格式")
      }

      // 验证输入数据结构
      if (!graphData.nodes || !Array.isArray(graphData.nodes) || !graphData.edges || !Array.isArray(graphData.edges)) {
        throw new Error("输入数据必须包含nodes和edges数组")
      }

      // 准备请求数据
      const requestData: AlgorithmRequest = {
        task_id: taskId,
        task_callback_url: "",
        input_params: {
          hgpms_params: {
            graph_data: graphData,  // 修改为 graph_data
            min_support: Number(config.min_support) || 0.05,
            max_pattern_size: Number(config.max_pattern_size) || 4
          }
        }
      }

      // 创建任务
      const createResponse = await fetch("http://172.16.4.151:1122/api/hgpms/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData)
      })

      if (!createResponse.ok) {
        const errorData = await createResponse.json()
        if (createResponse.status === 422) {
          const validationErrors = errorData.detail || []
          const errorMessages = validationErrors.map((err: any) => 
            `${err.loc?.join('.')}: ${err.msg}`
          ).join('\n')
          throw new Error(`数据验证错误:\n${errorMessages}`)
        }
        throw new Error(errorData.detail || "创建任务失败")
      }

      // 执行任务
      const executeResponse = await fetch(`http://172.16.4.151:1122/api/hgpms/execute/${taskId}`, {
        method: "POST"
      })

      if (!executeResponse.ok) {
        const errorData = await executeResponse.json()
        throw new Error(errorData.detail || "执行任务失败")
      }

      // 轮询获取结果
      let result
      let attempts = 0
      const maxAttempts = 60

      while (attempts < maxAttempts) {
        const getResultResponse = await fetch(`http://172.16.4.151:1122/api/hgpms/result/${taskId}`)
        
        if (!getResultResponse.ok) {
          const errorData = await getResultResponse.json()
          throw new Error(errorData.detail || "获取结果失败")
        }

        result = await getResultResponse.json()
        
        // 添加日志以便调试
        console.log(`第${attempts + 1}次尝试获取结果:`, result.task_status)

        if (result.task_status === "COMPLETED") {
          break
        } else if (result.task_status === "FAILED") {
          throw new Error(result.error_message || "任务执行失败")
        }

        await new Promise(resolve => setTimeout(resolve, 1000))
        attempts++
      }

      if (attempts >= maxAttempts) {
        throw new Error("任务执行超时")
      }

      // 添加调试日志
      console.log("API返回的完整结果:", JSON.stringify(result, null, 2))

      // 处理结果
      let resultText = ""
      let topPatternsText = ""
      let topPatterns: Pattern[] = []
      let outputParams: any = {}

      try {
        // 检查结果结构，更灵活地获取数据
        if (!result.output_params) {
          throw new Error("服务器返回的结果中缺少output_params字段")
        }
        
        // 获取hgpms_results
        outputParams = result.output_params.hgpms_results || {}
        console.log("处理的outputParams:", JSON.stringify(outputParams, null, 2))
        
        // 尝试找到patterns数组，可能在不同的路径下
        let patterns: Pattern[] = []
        
        // 可能的路径1: outputParams.results.patterns
        if (outputParams.frequent_patterns && Array.isArray(outputParams.frequent_patterns)) {
          patterns = outputParams.frequent_patterns
        } 
        // 可能的路径2: outputParams.patterns (直接在顶层)
        else if (Array.isArray(outputParams.frequent_patterns)) {
          patterns = outputParams.frequent_patterns
        }
        // 可能的路径3: 整个outputParams就是结果数组
        else if (Array.isArray(outputParams)) {
          patterns = outputParams
        }
        // 没有找到有效的patterns数组
        else {
          console.warn("无法在返回结果中找到patterns数组，使用空数组")
          patterns = []
        }
        
        // 获取execution_time，也可能在不同位置
        const executionTime = outputParams.execution_time || 
                             (typeof result.execution_time === 'number' ? result.execution_time : 0)
        
        // 获取pattern_growth_history，可能在不同位置
        const patternGrowthHistory = 
          (outputParams.results && outputParams.results.pattern_growth_history) || 
          outputParams.pattern_growth_history || 
          []
        
        // 生成结果摘要
        resultText = `模式挖掘完成：
发现的频繁模式数量: ${ patternGrowthHistory[0]}
模式挖掘增长历史: ${Array.isArray(patternGrowthHistory) ? patternGrowthHistory.join(' -> ') : '未知'}
执行时间: ${executionTime.toFixed(2)}秒`

        // 如果有模式，显示支持度最高的模式
        if (patterns.length > 0) {
          topPatterns = [...patterns]
            .sort((a, b) => (b.support || 0) - (a.support || 0))
            .slice(0, 5)

          topPatternsText = `发现的主要模式:
${topPatterns.map(pattern => {
  // 安全访问，防止undefined
  const id = pattern.id || '未知ID'
  const support = pattern.support || 0
  const nodes = pattern.node_types || {}
  
  // 处理edge_patterns，考虑它可能是一个对象数组
  let edgeText = '未知'
  if (pattern.edge_patterns && Array.isArray(pattern.edge_patterns)) {
    edgeText = pattern.edge_patterns.map(edge => 
      `${edge.source_type || '?'}-[${edge.edge_type || '?'}]->${edge.target_type || '?'} (${edge.count || 0})`
    ).join(', ')
  } else if (pattern.edge_patterns && typeof pattern.edge_patterns === 'object') {
    // 如果是对象而不是数组，用Object.entries处理
    edgeText = Object.entries(pattern.edge_patterns)
      .map(([key, value]) => `${key}(${value})`)
      .join(', ')
  }
  
  return `- 模式ID: ${id}
  支持度: ${(support * 100).toFixed(2)}%
  节点构成: ${Object.entries(nodes).map(([type, count]) => `${type}(${count})`).join(', ') || '未知'}
  边构成: ${edgeText}
  实例数量: ${(pattern.instances || []).length}`
}).join('\n')}`
        } else {
          topPatternsText = "未发现任何模式"
        }
      } catch (error: any) {
        console.error("处理结果时出错:", error)
        resultText = `执行完成，但无法解析结果: ${error.message || '未知错误'}`
        topPatternsText = "无可用模式数据"
        // 设置一个空对象避免后续引用错误
        outputParams = {}
      }

      // 紧急修复：完全移除复杂对象结构
      const emergencyFixResult = {
        result: `${resultText}\n\n${topPatternsText}`,
        steps: [],  // 完全移除steps
        executionTime: (typeof outputParams.execution_time === 'number') ? outputParams.execution_time : 0,
        details: {
          patterns: topPatterns.map(pattern => ({
            id: pattern.id || '未知ID',
            nodes: pattern.nodes || {},
            edges: pattern.edges || {},
            support: pattern.support || 0,
            instances: (pattern.instances || []).map(id => typeof id === 'string' ? id : '未知')
          })),
          patternGrowthHistory: Array.isArray(outputParams.pattern_growth_history) 
            ? outputParams.pattern_growth_history 
            : [],
          parameters: {},  // 简化为空对象
          metrics: []  // 移除所有metrics
        }
      };

      return emergencyFixResult;
    } catch (e) {
      throw e
    }
  }
} 